<template>
  <div class="relative">
    <el-icon class="absolute z-2 top-[50%] left-[50%] transform translate-x-[-50%] translate-y-[-50%]" size="26" color="red"
      ><LocationInformation
    /></el-icon>
    <div id="mapContainer" :style="{ width: props.width, height: props.height }"></div>
  </div>
</template>

<script setup lang="ts">
import { AMAP_MAP_KEY } from "@/config";
import AMapLoader from "@amap/amap-jsapi-loader";
import { shallowRef, ref, onMounted } from "vue";
import { LocationInformation } from "@element-plus/icons-vue";

interface Props {
  plugins?: string[]; //插件名称
  center: number[];
  zoom: number;
  width: string;
  height: string;
}

const emits = defineEmits(["getMap", "getLocation"]);

const props = withDefaults(defineProps<Props>(), {
  center: () => {
    return [105.602725, 37.076636];
  },
  zoom: 12,
  width: "100%",
  height: "400px",
  plugins: () => {
    return [];
  }
});

// ----构建地图
const map = shallowRef(null);

// ----高德组件
const amap = ref();

// ----初始化高德地图组件
const initAMap = async () => {
  amap.value = await AMapLoader.load({ key: AMAP_MAP_KEY, version: "2.0", plugins: [...props.plugins] });
};

// ----初始化地图
const initMap = async () => {
  map.value = new amap.value.Map("mapContainer", { viewMode: "2D", zoom: props.zoom, center: props.center });
  // 添加事件
  // 拖动事件
  (map.value as any).on("dragend", (ev: any) => {
    const location = [ev.lnglat.lng, ev.lnglat.lat].join(",");
    emits("getLocation", location);
  });
};

onMounted(async () => {
  await initAMap();
  await initMap();
  emits("getMap", { map: map.value, amap: amap.value });
});
</script>

<style></style>
